<?php
declare (strict_types=1);

namespace app\controller\v1;
use app\util\CacheHelper;
use app\util\Tools;
use think\annotation\route\Group;
use think\annotation\Route;
use think\facade\Db;

/**
 * 城市类接口
 * Class Area
 * @package app\controller\v1
 * @Group("v1/area")
 */
class Area extends Base
{
    /**
     * 获取所有
     * @Route("list", method="GET")
     */
    public function getList()
    {
        $cacheKeyP = config('cachekeys.fx_area_list') . ':PROVINCE';
        $cacheKeyC = config('cachekeys.fx_area_list') . ':CITY';
        $redis = new CacheHelper();
        $isHasP = $redis->get($cacheKeyP);
        if ($isHasP) {
            $provice = json_decode($isHasP, true);
        } else {
            $provice = Db::table('province')
                ->field(array('provinceID', 'province'))
                ->select();
            if (empty($provice)) {
                $provicelist = array();
                $citylist = array();
                $townlist = array();

                return json_ok(['provinceList' => $provicelist, 'cityList' => $citylist, 'townList' => $townlist], 200);
            }
            $provice = $provice->toArray();
            $redis->set($cacheKeyP, json_encode($provice));
        }

        $data = array();
        $data['provinceList'] = $provice;

        $isHasCity = $redis->get($cacheKeyC);
        if ($isHasCity) {
            $city = json_decode($isHasCity, true);
        } else {
            $citylist = Db::table('area')
                ->field(array('province_code', 'city_name', 'city_code', 'town_name', 'town_code', 'street_name', 'street_code'))
                ->select();
            if (empty($citylist)) {
                $citylist = array();
                $townlist = array();
                return json_ok(['provinceList' => $provice, 'cityList' => $citylist, 'townList' => $townlist], 200);
            }
            $city = $citylist->toArray();
            $redis->set($cacheKeyC, json_encode($city));
        }

        $citylistNew = $townlistNew = array();
        foreach ($city as $c) {
            $citylistNew[] = array('province_code' => $c['province_code'], 'city_name' => $c['city_name'], 'city_code' => $c['city_code']);
            $townlistNew[] = array('city_code' => $c['city_code'], 'town_name' => $c['town_name'], 'town_code' => $c['town_code'], 'street_name' => $c['street_name'], 'street_code' => $c['street_code']);
        }
        $data['cityList'] = $citylistNew;
        $data['townlist'] = $townlistNew;
        return json_ok($data, 200);
    }

}
